#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
os.environ['SQLALCHEMY_SILENCE_UBER_WARNING'] = '1'

import sys
sys.path.append('.')

from app import create_app
from models import db
from models.user import User
from models.session import UserSession
import logging

# 禁用SQLAlchemy日志
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)

def simple_login_test():
    app = create_app()
    with app.app_context():
        try:
            print("=== 登录功能测试 ===")
            
            # 查找用户
            user = User.query.filter_by(email='admin@example.com').first()
            if not user:
                print("❌ 用户不存在")
                return
            
            print(f"✅ 找到用户: {user.email}")
            
            # 验证密码
            if not user.check_password('admin123'):
                print("❌ 密码验证失败")
                return
            
            print("✅ 密码验证成功")
            
            # 检查用户状态
            if not user.is_active():
                print("❌ 用户账户被禁用")
                return
            
            print("✅ 用户状态正常")
            
            # 创建会话
            session = UserSession(
                user_id=user.id,
                ip_address='127.0.0.1',
                user_agent='Test Agent'
            )
            
            db.session.add(session)
            db.session.commit()
            
            print(f"✅ 会话创建成功: {session.token[:20]}...")
            
            # 测试用户字典转换
            user_dict = user.to_dict()
            print(f"✅ 用户数据转换成功，包含字段: {len(user_dict)} 个")
            
            print("\n🎉 登录功能测试全部通过！")
            
        except Exception as e:
            print(f"❌ 测试失败: {e}")
            import traceback
            traceback.print_exc()

if __name__ == '__main__':
    simple_login_test()